
var principal;
var salir;
var atras;

var estado = 0;
//0:Listado de tiendas
//1:Lista de Reportes
//2:formulario de consulta
//3:reporte en html
var tienda_id;
var tienda_text;
var reporte_text;
var parametro;

var obj;

var salir_handler = function(){
	logout();
	principal.removeAll(true);        	
	salir.hide();
	atras.hide();
	doLogin();
}
var atras_handler = function(){
	
	if(estado == 1){
		principal.remove("menuPanel");
		doTiendas();
		atras.hide();
	}else if(estado == 2){
		principal.remove("consultaForm");	
		doMenu();
	}else if(estado == 3){
		principal.remove("viewerPanel");
		entryPanel();
	}
}

var start = function(){
	salir = new Ext.Button({
        text: 'Salir',
        ui: 'decline-round',
        hidden: true,
        handler: salir_handler,
        scope: this
    });
	
	atras = new Ext.Button({
        text: 'Atras',
        ui: 'back',
        hidden: true,
        handler: atras_handler,
        scope: this
    });
	
	new Ext.Application({
        launch: function() {
	principal = new Ext.Panel({
	                fullscreen: true,
	                id:"principalPanel",
	                layout:{
	                	type:"vbox",
	                	pack:"center",
	                	align:"stretch"
	                },
	                dockedItems: [
	    		                  {
	    		                    xtype: "toolbar",
	    		                    dock: "top",
	    		                    title:"Sistema Ventas",
	    		                    items:[atras,{xtype:'spacer'},salir]
	    		                  }
	    		                  ]
	                
	            });
			doLogin();
        }});
	
	
	
};

var doLogin = function(){           
	estado = 0;
principal.add({
	xtype:"form",
	id:"loginForm",
	items:[{
    	xtype:"fieldset",	                	
    	title:"Iniciar Sesion",
    	defaults:{
    		labelWidth:"35%",
    		required:true
    	},
    	items:[{
    		xtype:"textfield",
    		name:"usuario",
    		label:"Usuario"
    		
    	},{
    		xtype:"passwordfield",
    		name:"clave",
    		label:"Clave"
    	}]
    },{
    	layout:{
    		type:"hbox",
        	pack:"center",
        	align:"stretch"		                	
    	},	                	
    	defaults:{
    		xtype:"button",
    		cls:"demobtn",
    		flex:1
    	},
    	items:[{	                    	
        	text:"Entrar",
        	ui:"action",
        	handler:validar_user_1
        },{	                    	
        	text:"Limpiar",
        	ui:"drastic",
        	handler:function(){
        		Ext.getCmp("loginForm").reset();
        		
        	}
        }]
    }]
});

principal.doLayout();

        
         
} 

//var validando = new Ext.LoadMask(Ext.getBody(), {msg: "Validando..."});

var validar_user_1 = function(){    		
	var user = Ext.getCmp("loginForm").getValues();
	if(Ext.util.Format.trim(user.usuario)!= "" && Ext.util.Format.trim(user.clave)!=""){
		//validando.show();
		Ext.getCmp("principalPanel").getEl().mask("Validando...");
		validar_user_2(user.usuario,user.clave);
	}
};


var validar_user_5 = function (result){
	Ext.getCmp("principalPanel").getEl().unmask();
	//validando.hide();
	if(result==null)
		Ext.Msg.alert("Sistema de Ventas","Usuario y/o clave incorrectos",Ext.emptyFn);
	else{
		obj = eval("(" + result + ')');		
		principal.remove("loginForm");		
		doTiendas();
	}
};

var isset_user = function (result){
	obj = eval("(" + result + ')');
	
	salir = new Ext.Button({
        text: 'Salir',
        ui: 'decline-round',
        hidden: true,
        handler: salir_handler,
        scope: this
    });
	atras = new Ext.Button({
        text: 'Atras',
        ui: 'back',
        hidden: true,
        handler: atras_handler,
        scope: this
    });
	new Ext.Application({
        launch: function() {
	principal = new Ext.Panel({
	                fullscreen: true,
	                id:"principalPanel",
	                layout:{
	                	type:"vbox",
	                	pack:"center",
	                	align:"stretch"
	                },
	                dockedItems: [
	    		                  {
	    		                    xtype: "toolbar",
	    		                    dock: "top",
	    		                    title:"Sistema Ventas",
	    		                    items:[atras,{xtype:'spacer'},salir]
	    		                  }
	    		                  ]
	                
	            });
		doTiendas();
        }});	
};

var show_error = function (){        	
	Ext.Msg.alert("Sistema de Ventas","Error de conexion",Ext.emptyFn);
	Ext.getCmp("principalPanel").getEl().unmask();
};

var show_alert = function (msg){        	
	Ext.Msg.alert("Sistema de Ventas",msg,Ext.emptyFn);
	Ext.getCmp("principalPanel").getEl().unmask();
};

var doTiendas = function (){
	estado = 0;
	salir.show();
	Ext.regModel('Tienda', {
		fields:['id', 'nombre','parent']
	});
	
	var tiendaStore = new Ext.data.Store({
		model:'Tienda',
		sorters:'nombre',
		getGroupString : function(record){
			return record.get('parent');
		},
		data :obj.tiendas
	});
	
	var tienda = new Ext.Panel({		
		fullscreen: true,
        id:"tiendaPanel",
        layout:'fit',
        cls: 'demo-list',
        items:[{
        	width:300,
        	height:500,
        	xtype:'list',
        	onItemDisclosure: true,
        	grouped:true,
        	store: tiendaStore,
        	itemTpl:'<div><strong>{nombre}</strong></div>',
        	listeners:{
        		itemtap: function(subList, subIdx, el, e){
        			var record = subList.getStore().getAt(subIdx);
        			tienda_id = record.get('id');
        			tienda_text = record.get('nombre');
            		//Ext.Msg.alert("Sistema de Ventas",record.get('nombre'),Ext.emptyFn);
        			principal.remove("tiendaPanel");        			
        			doMenu();
            	},
            	scope:this
        	}
        	
        }]
	});
	principal.add(tienda);
	principal.doLayout();
}

var doMenu = function (){
	estado = 1;
	atras.show();
	Ext.regModel('Menu', {
		fields:['menu', 'parametro','parent','textparent']
	});
	var i=0;
	for(i = 0; i < obj.reportes.length ;i++){
		obj.reportes[i].parent = obj.reportes[i].textparent +' > '+tienda_text;		
	}
	
	var menuStore = new Ext.data.Store({
		model:'Menu',
		sorters:'menu',
		getGroupString : function(record){
			return record.get('parent');
		},
		data :obj.reportes
	});
	
	var menu = new Ext.Panel({
		title: 'Reportes',
		fullscreen: true,
        id:"menuPanel",
        layout:'fit',
        cls: 'demo-list',
        items:[{
        	width:300,
        	height:500,
        	xtype:'list',
        	onItemDisclosure: true,
        	grouped:true,
        	store: menuStore,
        	itemTpl:'<div><strong>{menu}</strong></div>',
        	listeners:{
        		itemtap: function(subList, subIdx, el, e){
        			var record = subList.getStore().getAt(subIdx);
        			reporte_text = record.get('menu');
        			parametro = record.get('parametro');            		
        			principal.remove("menuPanel"); 
        			entryPanel();
        			//doConsulta();
            	},
            	scope:this
        	}
        	
        }]
	});
	principal.add(menu);
	principal.doLayout();
}

var entryPanel = function(){
	estado = 2;	
	if(parametro=='reporteventas'){
		reporteVentasPanel();
	}else if(parametro=='reportestock'){
		reporteStockPanel();
	}else if(parametro=='prendasvendidas'){
		prendasVendidasPanel();
	}else if(parametro=='resumen'){
		resumenPanel();
	}
	
}

var resumenPanel = function(){
	principal.add({
		xtype:"form",
		id:"consultaForm",		
		items:[{
	    	xtype:"fieldset",	                	
	    	title:tienda_text+" - "+reporte_text,	    	
	    	defaults:{
	    		labelWidth:"35%",
	    		required:true
	    	},
	    	items:[{
	    		xtype:"datepickerfield",
	    		name:"desde",
	    		label:"Fecha",
	    		picker:{yearFrom: 2010}
	    	}]
	    },{
	    	layout:{
	    		type:"hbox",
	        	pack:"center",
	        	align:"stretch"		                	
	    	},	                	
	    	defaults:{
	    		xtype:"button",
	    		cls:"demobtn",
	    		flex:1
	    	},
	    	items:[{	                    	
	        	text:"Buscar",
	        	ui:"confirm",
	        	handler:enviar_intervalo
	        }]
	    }]
	});

	principal.doLayout();
}

var prendasVendidasPanel = function(){
	
	principal.add({
		xtype:"form",
		id:"consultaForm",		
		items:[{
	    	xtype:"fieldset",	                	
	    	title:tienda_text+" - "+reporte_text,	    	
	    	defaults:{
	    		labelWidth:"35%",
	    		required:true
	    	},
	    	items:[{
	    		xtype:"datepickerfield",
	    		name:"desde",
	    		label:"Desde",
	    		picker:{yearFrom: 2010}
	    	},{
	    		xtype:"datepickerfield",
	    		name:"hasta",
	    		label:"Hasta",
	    		picker:{yearFrom: 2010}
	    	}]
	    },{
	    	layout:{
	    		type:"hbox",
	        	pack:"center",
	        	align:"stretch"		                	
	    	},	                	
	    	defaults:{
	    		xtype:"button",
	    		cls:"demobtn",
	    		flex:1
	    	},
	    	items:[{	                    	
	        	text:"Buscar",
	        	ui:"confirm",
	        	handler:enviar_intervalo
	        }]
	    }]
	});

	principal.doLayout();
}

var reporteStockPanel = function(){
	
	principal.add({
		xtype:"form",
		id:"consultaForm",		
		items:[{
	    	xtype:"fieldset",	                	
	    	title:tienda_text+" - "+reporte_text,	    	
	    	defaults:{
	    		labelWidth:"35%",
	    		required:true
	    	},
	    	items:[{
	    		xtype:"datepickerfield",
	    		name:"desde",
	    		label:"Desde",
	    		picker:{yearFrom: 2010}
	    	}]
	    },{
	    	layout:{
	    		type:"hbox",
	        	pack:"center",
	        	align:"stretch"		                	
	    	},	                	
	    	defaults:{
	    		xtype:"button",
	    		cls:"demobtn",
	    		flex:1
	    	},
	    	items:[{	                    	
	        	text:"Buscar",
	        	ui:"confirm",
	        	handler:enviar_intervalo
	        }]
	    }]
	});

	principal.doLayout();
}

var reporteVentasPanel = function(){
	
	principal.add({
		xtype:"form",
		id:"consultaForm",		
		items:[{
	    	xtype:"fieldset",	                	
	    	title:tienda_text+" - "+reporte_text,	    	
	    	defaults:{
	    		labelWidth:"35%",
	    		required:true
	    	},
	    	items:[{
	    		xtype:"datepickerfield",
	    		name:"desde",
	    		label:"Desde",
	    		picker:{yearFrom: 2010}
	    	},{
	    		xtype:"datepickerfield",
	    		name:"hasta",
	    		label:"Hasta",
	    		picker:{yearFrom: 2010}
	    	}]
	    },{
	    	layout:{
	    		type:"hbox",
	        	pack:"center",
	        	align:"stretch"		                	
	    	},	                	
	    	defaults:{
	    		xtype:"button",
	    		cls:"demobtn",
	    		flex:1
	    	},
	    	items:[{	                    	
	        	text:"Buscar",
	        	ui:"confirm",
	        	handler:enviar_intervalo
	        }]
	    }]
	});

	principal.doLayout();
}

var enviar_intervalo = function(){
	
	var intervalo = Ext.getCmp("consultaForm").getValues();
	
	if(intervalo.desde!= null && intervalo.hasta!=null){		
		Ext.getCmp("principalPanel").getEl().mask("Cargando...");	
		if(parametro=='reporteventas'){
			HtmlReportViewer("reports/tienda_ventas",{"desde":intervalo.desde.format('Y-m-d'), "hasta":intervalo.hasta.format('Y-m-d'),"tienda_id":tienda_id,"tienda":tienda_text},0);					
		}else if(parametro=='prendasvendidas'){
			HtmlReportViewer("reports/prendas_vendidas",{"desde":intervalo.desde.format('Y-m-d'), "hasta":intervalo.hasta.format('Y-m-d'),"tienda_id":tienda_id,"tienda":tienda_text},0);
		}
				
	}
	
	if(intervalo.desde!= null){		
		Ext.getCmp("principalPanel").getEl().mask("Cargando...");		
		if(parametro=='reportestock'){
			HtmlReportViewer("reports/reporte_stock",{"desde":intervalo.desde.format('Y-m-d'),"tienda_id":tienda_id,"tienda":tienda_text},1);		
		}else if(parametro=='resumen'){
			getBalanceTienda(intervalo.desde.format('Y-m-d'),tienda_id);
		}
				
	}
};

var doIframe = function(url){
	estado=3;
	Ext.getCmp("principalPanel").getEl().unmask();
	principal.remove("consultaForm");
	var viewer = new Ext.Panel({
				        fullscreen: true,
				        layout:'fit',
				        id:'viewerPanel',
				        html: '<iframe src="'+url+'" width="100%" height="100%"  ></iframe>'
				    });
	principal.add(viewer);
	principal.doLayout();
}

var doBalance = function(result){
	estado=3;
	Ext.getCmp("principalPanel").getEl().unmask();
	principal.remove("consultaForm");
	
	var json = eval("(" + result + ')');
	
	json[0].title = tienda_text+" - "+reporte_text;
	
	Ext.regModel('Balance', {
		fields:['descripcion','value','title']
	});	
	
	var balanceStore = new Ext.data.Store({
		model:'Balance',		
		getGroupString : function(record){
			return record.get('title');
		},
		data :[{descripcion:'Saldo inicial', value:json[0].saldoinicial,title:json[0].title},
		       {descripcion:'Ingreso ventas', value:json[0].ingresoventas,title:json[0].title},
		       {descripcion:'Ingreso separaciones', value:json[0].ingresoseparaciones,title:json[0].title},
		       {descripcion:'Gastos', value:json[0].gastos,title:json[0].title},
		       {descripcion:'Saldo', value:json[0].balance,title:json[0].title}
		]
	});
	
	var balance = new Ext.Panel({
		title: 'Reportes',
		fullscreen: true,
        id:"viewerPanel",
        layout:'fit',
        cls: 'demo-list',
        items:[{
        	width:300,
        	height:500,
        	xtype:'list',
        	onItemDisclosure: false,
        	grouped:true,
        	store: balanceStore,
        	itemTpl:'<div><strong>{descripcion} : </strong>{value}</div>'        	
        }]
	});
	principal.add(balance);
	principal.doLayout();
}